package com.jwaoo.chat.session.snap;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.dx.as.UI;
import com.dx.as.upload.DownloadManager;
import com.dx.as.upload.OnDownloadListener;
import com.jwaoo.chat.ChatConstants;
import com.jwaoo.chat.Message;
import com.jwaoo.chat.R;
import com.jwaoo.chat.bitmap.BitmapDecoder;
import com.jwaoo.chat.bitmap.ImageUtil;
import com.jwaoo.chat.data.db.MessageHandler;
import com.jwaoo.chat.ui.imageview.BaseZoomableImageView;
import com.jwaoo.media.dialog.CustomAlertDialog;

/**
 * 查看阅后即焚消息原图
 */
public class WatchSnapChatPictureActivity extends UI {
    private static final String INTENT_EXTRA_IMAGE = "INTENT_EXTRA_IMAGE";

    private Handler handler;
    private Message message;
    private View loadingLayout;
    private BaseZoomableImageView image;
    protected CustomAlertDialog alertDialog;

    private static WatchSnapChatPictureActivity instance;

    public static void start(Context context, Message message) {
        Intent intent = new Intent();
        intent.putExtra(INTENT_EXTRA_IMAGE, message);
        intent.setClass(context, WatchSnapChatPictureActivity.class);
        context.startActivity(intent);
    }

    public static void destroy() {
        if (instance != null) {
            instance.finish();
            instance = null;
        }
    }

    @Override
    protected void onActivityCreate(Bundle savedInstanceState) {
        setContentView(R.layout.nim_watch_snapchat_activity);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        onParseIntent();
        findViews();

        handler = new Handler();
        requestOriImage();

        instance = this;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        instance = null;
    }

    private void onParseIntent() {
        this.message = (Message) getIntent().getSerializableExtra(INTENT_EXTRA_IMAGE);
    }

    private void findViews() {
        alertDialog = new CustomAlertDialog(this);
        loadingLayout = findViewById(R.id.loading_layout);
        image = (BaseZoomableImageView) findViewById(R.id.watch_image_view);
    }

    private void requestOriImage() {
        if (isOriginImageHasDownloaded(message)) {
            onDownloadSuccess(message);
            return;
        }
        // async download original image
        onDownloadStart(message);
//        NIMClient.getService(MsgService.class).downloadAttachment(message, false);
    }

    private boolean isOriginImageHasDownloaded(final Message message) {
        if (message.getAttachment().getAttachstate() == ChatConstants.transferred &&
                !TextUtils.isEmpty(message.getAttachment().getPath())) {
            return true;
        }

        return false;
    }

    /**
     * ******************************** 设置图片 *********************************
     */

    private void setThumbnail() {
        String path =  message.getAttachment().getThumbPath();
        if (!TextUtils.isEmpty(path)) {
            Bitmap bitmap = BitmapDecoder.decodeSampledForDisplay(path);
            bitmap = ImageUtil.rotateBitmapInNeeded(path, bitmap);
            if (bitmap != null) {
                image.setImageBitmap(bitmap);
                return;
            }
        }

        image.setImageBitmap(ImageUtil.getBitmapFromDrawableRes(getImageResOnLoading()));
    }

    private void setImageView(final Message msg) {
        String path = msg.getAttachment().getPath();
        if (TextUtils.isEmpty(path)) {
            image.setImageBitmap(ImageUtil.getBitmapFromDrawableRes(getImageResOnLoading()));
            return;
        }

        Bitmap bitmap = BitmapDecoder.decodeSampledForDisplay(path, false);
        bitmap = ImageUtil.rotateBitmapInNeeded(path, bitmap);
        if (bitmap == null) {
            Toast.makeText(this, R.string.picker_image_error, Toast.LENGTH_LONG).show();
            image.setImageBitmap(ImageUtil.getBitmapFromDrawableRes(getImageResOnFailed()));
        } else {
            image.setImageBitmap(bitmap);
        }
    }

    private int getImageResOnLoading() {
        return R.drawable.nim_image_default;
    }

    private int getImageResOnFailed() {
        return R.drawable.nim_image_download_failed;
    }

    /**
     * ********************************* 下载 ****************************************
     */
//
//    private void registerObservers(boolean register) {
//        NIMClient.getService(MsgServiceObserve.class).observeMsgStatus(statusObserver, register);
//    }
//
//    private Observer<Message> statusObserver = new Observer<Message>() {
//        @Override
//        public void onEvent(IMMessage msg) {
//            if (!msg.isTheSame(message) || isDestroyedCompatible()) {
//                return;
//            }
//            if (msg.getAttachStatus() == AttachStatusEnum.transferred && isOriginImageHasDownloaded(msg)) {
//                onDownloadSuccess(msg);
//            } else if (msg.getAttachStatus() == AttachStatusEnum.fail) {
//                onDownloadFailed();
//            }
//        }
//    };

    private void onDownloadStart(final Message msg) {
        setThumbnail();
        if(TextUtils.isEmpty(msg.getAttachment().getPath())){
            loadingLayout.setVisibility(View.VISIBLE);
        } else {
            loadingLayout.setVisibility(View.GONE);
        }
        MessageHandler.getInstace(getApplicationContext()).handlerAttachmentMessage(msg);
        DownloadManager.addDownloadListener(msg.getMsgid(), new OnDownloadListener() {
            @Override
            public void onDownloadFailed() {

            }

            @Override
            public void onDownSuccess() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        message.getAttachment().setAttachstate(ChatConstants.transferred);;
                        onDownloadSuccess(message);
                    }
                });
            }

            @Override
            public void onDownProgress(long progress, long total) {
                Log.e("===",progress+"  /  "+total);
            }
        });
    }

    private void onDownloadSuccess(final Message msg) {
        loadingLayout.setVisibility(View.GONE);
        handler.post(new Runnable() {

            @Override
            public void run() {
                setImageView(msg);
            }
        });
    }

    private void onDownloadFailed() {
        loadingLayout.setVisibility(View.GONE);
        image.setImageBitmap(ImageUtil.getBitmapFromDrawableRes(getImageResOnFailed()));
        Toast.makeText(this, R.string.download_picture_fail, Toast.LENGTH_LONG).show();
    }
}
